package de.pernpas.calendar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import de.pernpas.calendar.common.CalUtils;
import de.pernpas.calendar.entity.Event;
import de.pernpas.calendar.service.EventService;

public class ImportCsv extends HttpServlet {

	 /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static final Logger log = Logger.getLogger(FileUpload.class.getName());

	  public void doPost(HttpServletRequest req, HttpServletResponse res)
	      throws ServletException, IOException {
	    try {
	      ServletFileUpload upload = new ServletFileUpload();
	      res.setContentType("text/plain");

	      FileItemIterator iterator = upload.getItemIterator(req);
	      while (iterator.hasNext()) {
	        FileItemStream item = iterator.next();
	        InputStream stream = item.openStream();

	        if (item.isFormField()) {
	          log.warning("Got a form field: " + item.getFieldName());
	        } else {
	          log.warning("Got an uploaded file: " + item.getFieldName() +
	                      ", name = " + item.getName());

	          BufferedReader in = new BufferedReader(new InputStreamReader(stream));
	          String zeile = null;
	          while ((zeile = in.readLine()) != null) {
	  			String[] splits = zeile.split(";");
	  			if(splits.length == 4 | splits.length == 5 ){
	  				log.info("Zeile ist OK");
	  				CalUtils cu = new CalUtils();
	  				Date date = cu.getDateWithTime(splits[2]);
	  				String location = "";
	  				if(splits.length == 5){
	  					location = cleanString(splits[4]);
	  				}
	  				String eventName = cleanString(splits[3]); 
	  				Event event = new Event(date, location, eventName, "");
	  				EventService.insertEvent(event);
	  			}else{
	  				log.warning("Zeile hat nicht 4/5 splits: " + zeile);	  				
	  			}
	  		  }
	        }
	      }
	    } catch (Exception ex) {
	      throw new ServletException(ex);
	    }
	  }

	  /**
	   * Das f�hrende und letzte Anf�hrungszeichen abschneiden und die Stringl�nge auf 500 begrenzen, weil 
	   * in die Google APS DB keine l�ngeren Strings gespeichert werden k�nnen. Wenn doch l�ngere Strings 
	   * gespeichert werden sollen, dann "TEXT" benutzen.
	   * 
	   * @param str
	   * @return
	   */
	  private String cleanString(String str) {
		String result = "";
		log.fine("Bereinige String: \"" + str + "\"");
		if (str.length() > 0) {
			result = str.substring(1);
			result = result.substring(0, result.length() - 1);
		}
		if(result.length() > 500) result = result.substring(0, 499);
		log.fine("Bereinigter String: " + result);
		return result;
	}

}
